<template>
    <div class="user-client-content">
        <!-- 主要内容区域 -->
        <div class="main-content">
            <div class="content-card">
                <div class="card-header">
                    <el-icon class="header-icon">
                        <Location />
                    </el-icon>
                    <h2>添加送达地址</h2>
                </div>

                <form @submit.prevent="saveAddress" class="address-form">
                    <div class="form-grid">
                        <div class="form-group">
                            <label for="recipientId" class="form-label">收件人姓名</label>
                            <el-input id="recipientId" v-model="addressForm.recipientId" placeholder="请输入收件人姓名"
                                clearable class="form-input" />
                        </div>
                        <div class="form-group">
                            <label for="phone" class="form-label">联系方式</label>
                            <el-input id="phone" v-model="addressForm.phone" placeholder="请输入联系电话" clearable
                                class="form-input" />
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="pickupAddress" class="form-label">取货地点</label>
                        <el-select id="pickupAddress" v-model="addressForm.pickupAddress" placeholder="请选择取货地点"
                            clearable class="form-select">
                            <el-option v-for="point in pickupPoints" :key="point.value" :value="point.value"
                                :label="point.label">
                                <div class="location-option">{{ point.label }}</div>
                            </el-option>
                        </el-select>
                    </div>

                    <div class="form-group">
                        <label for="pickupDetails" class="form-label">取货详情</label>
                        <el-input id="pickupDetails" v-model="addressForm.pickupDetails" type="textarea" :rows="2"
                            placeholder="请输入取货详情信息（如：取件码、商品描述、特殊要求等）" maxlength="200" show-word-limit
                            class="form-textarea" />
                    </div>

                    <div class="form-group">
                        <label for="deliveryAddress" class="form-label">送达地点</label>
                        <el-select id="deliveryAddress" v-model="addressForm.deliveryAddress" placeholder="请选择送达地点"
                            clearable class="form-select">
                            <el-option v-for="point in deliveryPoints" :key="point.value" :value="point.value"
                                :label="point.label">
                                <div class="location-option">{{ point.label }}</div>
                            </el-option>
                        </el-select>
                    </div>

                    <div class="form-group">
                        <label for="deliverDetails" class="form-label">送达详情</label>
                        <el-input id="deliverDetails" v-model="addressForm.deliverDetails" type="textarea" :rows="2"
                            placeholder="请输入送达详情信息（如：具体地址、联系方式、特殊要求等）" maxlength="200" show-word-limit
                            class="form-textarea" />
                    </div>

                    <div class="form-group">
                        <label for="appointmentTime" class="form-label">预约时间</label>
                        <el-select id="appointmentTime" v-model="addressForm.appointmentTime" placeholder="请选择预约时间"
                            clearable class="form-select">
                            <el-option v-for="time in appointmentTimes" :key="time.value" :label="time.label"
                                :value="time.value" />
                        </el-select>
                    </div>

                    <el-button type="primary" @click="saveAddress" class="save-button">
                        <el-icon class="mr-2">
                            <Check />
                        </el-icon>
                        保存
                    </el-button>
                </form>
            </div>

            <div class="car">
                <div class="car-header">
                    <el-icon class="car-header-icon">
                        <Box />
                    </el-icon>
                    <h2>我的订单</h2>
                </div>

                <div class="orders-list">
                    <div v-for="order in ordersData" :key="order.id" class="order-card">
                        <div class="order-header">
                            <div class="recipient-info">
                                <el-icon :class="['status-icon', order.status]">
                                    <Clock v-if="order.status === 'pending'" />
                                    <Check v-else />
                                </el-icon>
                                <span class="recipient-name">{{ order.requesterName }} {{ order.requesterPhone }}</span>
                            </div>
                            <div :class="['status-tag', order.status]">{{ getStatusText(order.status) }}</div>
                        </div>

                        <div class="address-container">
                            <div class="pickup-address">
                                <el-icon class="address-icon">
                                    <Location />
                                </el-icon>
                                <div class="address-content">
                                    <div class="address-label">取货点:</div>
                                    <div class="primary-address">{{ getLocationNameById(order.pickupAddress) }}</div>
                                    <div class="detailed-address">{{ order.pickupDetails }}</div>
                                </div>
                            </div>

                            <div class="delivery-address">
                                <el-icon class="address-icon">
                                    <Location />
                                </el-icon>
                                <div class="address-content">
                                    <div class="address-label">送达点:</div>
                                    <div class="primary-address">{{ getLocationNameById(order.deliveryAddress) }}</div>
                                    <div class="detailed-address">{{ order.deliveryDetails }}</div>
                                </div>
                            </div>
                        </div>

                        <div class="order-footer">
                            <div class="time-info">
                                <span class="order-time">预约时间: {{ formatTimestamp(order.scheduledTime) }}</span>
                                <span v-if="order.completedTime" class="completed-time">完成时间: {{
                                    formatTimestamp(order.completedTime) }}</span>
                            </div>
                            <div class="courier-info" v-if="order.courierName">
                                <span class="courier-label">配送员:</span>
                                <span class="courier-name">{{ order.courierName }}</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Location, Check, Box, Clock } from '@element-plus/icons-vue'
import { createDeliveryOrder, getLocationList, getDeliveryOrders } from '@/api/delivery'
import type { CreateDeliveryOrderRequest, LocationInfo } from '@/api/delivery/models'

// 表单数据
const addressForm = reactive({
    recipientId: '',
    phone: '',
    pickupAddress: '',
    pickupDetails: '',
    deliveryAddress: '',
    deliverDetails: '',
    appointmentTime: ''
})

// 地点数据（从API获取）
const locationData = reactive<LocationInfo[]>([])

// 取货点选项（isPickupPoint为true的地点）
const pickupPoints = computed(() => {
    const points = locationData
        .filter(location => location.isPickupPoint)
        .map(location => ({
            value: location.locationId,
            label: location.name,
            detailedAddress: location.detailedAddress,
            contactPhone: location.contactPhone,
            businessHours: location.businessHours
        }))
    return points
})

// 送达地点选项（所有地点都可以作为送达点）
const deliveryPoints = computed(() => {
    const points = locationData.map(location => ({
        value: location.locationId,
        label: location.name,
        detailedAddress: location.detailedAddress,
        type: location.type
    }))
    return points
})

// 获取地点类型标签
const getTypeLabel = (type: string) => {
    const typeMap: Record<string, string> = {
        'kuaidizhan': '快递站',
        'chaoshi': '超市',
        'sushe': '宿舍楼'
    }
    return typeMap[type] || type
}

// 根据地点ID获取地点名称
const getLocationNameById = (locationId: string) => {
    const location = locationData.find(loc => loc.locationId === locationId)
    return location ? location.name : '未知地点'
}

// 格式化时间戳
const formatTimestamp = (timestamp: number | null) => {
    if (!timestamp) return '未完成'
    const date = new Date(timestamp * 1000)
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    })
}

// 获取状态文本
const getStatusText = (status: string) => {
    const statusMap: Record<string, string> = {
        'pending': '待配送',
        'in_progress': '配送中',
        'delivered': '已送达',
        'cancelled': '已取消'
    }
    return statusMap[status] || status
}

// 默认地点数据
const defaultLocationData: LocationInfo[] = [
    { locationId: 'jeijiao103', name: '阶教103', detailedAddress: '地图1', type: 'kuaidizhan', note: null, latitude: null, longitude: null, isPickupPoint: true, contactPhone: '11341223435', businessHours: '9:00-19:00', status: 1 },
    { locationId: 'huirunchaoshi', name: '徽润超市', detailedAddress: '地图2', type: 'chaoshi', note: null, latitude: null, longitude: null, isPickupPoint: true, contactPhone: '12446523245', businessHours: '6:00-23:00', status: 1 },
    { locationId: 'g3dong', name: 'G3栋', detailedAddress: '地图4', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 },
    { locationId: 'g4dong', name: 'G4栋', detailedAddress: '地图5', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 },
    { locationId: 'g5dong', name: 'G5栋', detailedAddress: '地图6', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 },
    { locationId: 'g6dong', name: 'G6栋', detailedAddress: '地图7', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 },
    { locationId: 'g7dong', name: 'G7栋', detailedAddress: '地图8', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 },
    { locationId: 'g8dong', name: 'G8栋', detailedAddress: '地图9', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 },
    { locationId: 'g9dong', name: 'G9栋', detailedAddress: '地图10', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 },
    { locationId: 'g10dong', name: 'G10栋', detailedAddress: '地图11', type: 'sushe', note: null, latitude: null, longitude: null, isPickupPoint: false, contactPhone: null, businessHours: null, status: 1 }
]

// 获取地点数据
const fetchLocationData = async () => {
    try {
        const response = await getLocationList()
        if (response && Array.isArray(response)) {
            locationData.splice(0, locationData.length, ...response)
        } else {
            locationData.splice(0, locationData.length, ...defaultLocationData)
        }
    } catch (error) {
        locationData.splice(0, locationData.length, ...defaultLocationData)
    }
}

// 获取订单数据
const fetchOrdersData = async () => {
    try {
        const response = await getDeliveryOrders()
        console.log(response);
        if (response && Array.isArray(response)) {
            ordersData.splice(0, ordersData.length, ...response)
        } else {
            ordersData.splice(0, ordersData.length, ...defaultOrdersData)
        }
    } catch (error) {
        ordersData.splice(0, ordersData.length, ...defaultOrdersData)
    }
}

// 预约时间选项
const appointmentTimes = [
    { label: '立即配送', value: 'immediate' },
    { label: '今天上午 (9:00-12:00)', value: 'today_morning' },
    { label: '今天下午 (14:00-18:00)', value: 'today_afternoon' },
    { label: '今天晚上 (18:00-21:00)', value: 'today_evening' },
    { label: '明天上午 (9:00-12:00)', value: 'tomorrow_morning' },
    { label: '明天下午 (14:00-18:00)', value: 'tomorrow_afternoon' },
    { label: '明天晚上 (18:00-21:00)', value: 'tomorrow_evening' },
    { label: '后天上午 (9:00-12:00)', value: 'day_after_morning' },
    { label: '后天下午 (14:00-18:00)', value: 'day_after_afternoon' },
    { label: '后天晚上 (18:00-21:00)', value: 'day_after_evening' }
]

// 默认订单数据
const defaultOrdersData = [
    {
        id: 'DL20230615001',
        requesterId: 'REQ001',
        requesterName: '张三',
        requesterPhone: '138****1234',
        courierId: 'COU001',
        courierName: '王师傅',
        courierPhone: '139****5678',
        status: 'pending',
        pickupAddress: 'jeijiao103',
        pickupDetails: '1号柜，取件码：A1B2C3',
        deliveryAddress: 'g3dong',
        deliveryDetails: '3楼305室',
        scheduledTime: 1686805800, // 2023-06-15 10:30:00
        completedTime: null
    },
    {
        id: 'DL20230614001',
        requesterId: 'REQ002',
        requesterName: '李四',
        requesterPhone: '139****5678',
        courierId: 'COU002',
        courierName: '李师傅',
        courierPhone: '137****9012',
        status: 'delivered',
        pickupAddress: 'huirunchaoshi',
        pickupDetails: '2号柜，取件码：D4E5F6',
        deliveryAddress: 'g4dong',
        deliveryDetails: '二楼自习室',
        scheduledTime: 1686720000, // 2023-06-14 14:20:00
        completedTime: 1686723600 // 2023-06-14 15:20:00
    }
]

// 订单数据（从API获取）
const ordersData = reactive<any[]>([])

// 表单验证
const validateForm = () => {
    if (!addressForm.recipientId.trim()) {
        ElMessage.error('请输入收件人姓名')
        return false
    }
    if (!addressForm.phone.trim()) {
        ElMessage.error('请输入联系方式')
        return false
    }
    if (!/^1[3-9]\d{9}$/.test(addressForm.phone)) {
        ElMessage.error('请输入正确的手机号码')
        return false
    }
    if (!addressForm.pickupAddress) {
        ElMessage.error('请选择取货地点')
        return false
    }
    if (!addressForm.pickupDetails) {
        ElMessage.error('请选择取货商品信息')
        return false
    }
    if (!addressForm.deliveryAddress) {
        ElMessage.error('请选择送达地点')
        return false
    }
    if (!addressForm.deliverDetails) {
        ElMessage.error('请选择送货详情')
        return false
    }
    if (!addressForm.appointmentTime) {
        ElMessage.error('请选择预约时间')
        return false
    }
    return true
}

// 保存地址
const saveAddress = async () => {
    if (!validateForm()) return

    // 构建完整的表单数据
    const formData = {
        ...addressForm,
        timestamp: Math.floor(Date.now() / 1000)
    }

    try {
        // 构建API请求数据
        const requestData: CreateDeliveryOrderRequest = {
            recipientId: formData.recipientId,
            phone: formData.phone,
            pickupAddress: formData.pickupAddress,
            pickupDetails: formData.pickupDetails,
            deliveryAddress: formData.deliveryAddress,
            deliverDetails: formData.deliverDetails,
            appointmentTime: formData.appointmentTime,
            timestamp: formData.timestamp
        }

        // 调用创建配送订单API
        const response = await createDeliveryOrder(requestData)
        if (response.success) {
            ElMessage.success('配送订单创建成功！')
            console.log('订单ID:', response.data?.orderId)

            // 创建成功后刷新订单列表
            await fetchOrdersData()
        } else {
            ElMessage.error(response.message || '创建失败')
        }

        // 重置表单
        Object.assign(addressForm, {
            recipientId: '',
            phone: '',
            pickupAddress: '',
            pickupDetails: '',
            deliveryAddress: '',
            deliverDetails: '',
            appointmentTime: ''
        })
    } catch (error) {
        ElMessage.error('保存失败，请重试')
    }
}

// 组件挂载时获取数据
onMounted(async () => {
    await fetchLocationData()
    await fetchOrdersData()
})
</script>

<style scoped>
.user-client-content {
    padding: 20px;
}

.main-content {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
    max-width: 1200px;
    margin: 0 auto;
}

@media (min-width: 1024px) {
    .main-content {
        grid-template-columns: 1fr 1fr;
    }
}

.content-card {
    background: white;
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    width: 100%;
    height: fit-content;
}

.card-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f0f0;
}

.header-icon {
    font-size: 1.5rem;
    color: #3498db;
    margin-right: 12px;
}

.card-header h2 {
    margin: 0;
    font-size: 1.5rem;
    color: #333;
    font-weight: 600;
}

.address-form {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.form-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 16px;
}

@media (min-width: 768px) {
    .form-grid {
        grid-template-columns: 1fr 1fr;
    }
}

.form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.form-label {
    font-weight: 600;
    color: #333;
    font-size: 14px;
}

.form-input {
    width: 100%;
}

.form-textarea {
    width: 100%;
}

.form-select {
    width: 100%;
}

.input-with-icon {
    position: relative;
}

.input-icon {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #9ca3af;
    font-size: 20px;
    pointer-events: none;
    z-index: 10;
}

.input-with-icon :deep(.el-input__inner) {
    padding-left: 40px;
}

.mr-2 {
    margin-right: 8px;
}

.save-button {
    width: 100%;
    height: 48px;
    font-size: 1.1rem;
    font-weight: 600;
    border-radius: 8px;
    background: #27ae60;
    border: none;
    transition: all 0.3s ease;
}

.save-button:hover {
    box-shadow: 0 8px 20px rgba(39, 174, 96, 0.4);
    background: #229954;
}

/* 我的订单区域样式 */
.car {
    background: white;
    border-radius: 16px;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    width: 100%;
    height: fit-content;
}

.car-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 2px solid #f0f0f0;
}

.car-header-icon {
    font-size: 1.5rem;
    color: #3498db;
    margin-right: 12px;
}

.car-header h2 {
    margin: 0;
    font-size: 1.5rem;
    color: #333;
    font-weight: 600;
}

.orders-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.order-card {
    border: 1px solid #e0e0e0;
    border-radius: 12px;
    padding: 20px;
    background: #fafafa;
    transition: all 0.3s ease;
}

.order-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
}

.order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
}

.recipient-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.status-icon {
    font-size: 1.2rem;
}

.status-icon.pending {
    color: #f39c12;
}

.status-icon.delivered {
    color: #27ae60;
}

.recipient-name {
    font-weight: 600;
    color: #333;
}

.status-tag {
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
}

.status-tag.pending {
    background: #fef3cd;
    color: #856404;
}

.status-tag.delivered {
    background: #d1edff;
    color: #0c5460;
}

.address-container {
    display: flex;
    gap: 20px;
    margin-bottom: 15px;
}

.pickup-address,
.delivery-address {
    display: flex;
    align-items: flex-start;
    gap: 8px;
    flex: 1;
}

.pickup-address {
    border-right: 1px solid #f0f0f0;
    padding-right: 20px;
}

@media (max-width: 768px) {
    .address-container {
        flex-direction: column;
        gap: 12px;
    }

    .pickup-address {
        border-right: none;
        border-bottom: 1px solid #f0f0f0;
        padding-right: 0;
        padding-bottom: 12px;
    }
}

.address-icon {
    color: #9ca3af;
    font-size: 1rem;
    margin-top: 2px;
}

.address-content {
    flex: 1;
}

.address-label {
    font-size: 0.8rem;
    color: #9ca3af;
    margin-bottom: 2px;
    font-weight: 500;
}

.primary-address {
    font-weight: 500;
    color: #333;
    margin-bottom: 4px;
}

.detailed-address {
    font-size: 0.9rem;
    color: #666;
    margin-left: 8px;
}

.order-footer {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding-top: 15px;
    border-top: 1px solid #e0e0e0;
}

.time-info {
    display: flex;
    flex-direction: column;
    gap: 4px;
}

.order-time {
    font-size: 0.9rem;
    color: #666;
}

.completed-time {
    font-size: 0.9rem;
    color: #28a745;
}

.courier-info {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-top: 4px;
}

.courier-label {
    font-size: 0.9rem;
    color: #666;
}

.courier-name {
    background: #e6f7ff;
    border: 1px solid #91d5ff;
    border-radius: 6px;
    padding: 4px 8px;
    font-weight: 600;
    color: #1890ff;
    font-size: 0.9rem;
}

/* 地点选项样式 */
.location-option {
    padding: 4px 0;
    line-height: 1.4;
}

.location-name {
    font-weight: 600;
    color: #333;
    margin-bottom: 2px;
    font-size: 14px;
}

.location-details {
    display: flex;
    flex-direction: column;
    gap: 1px;
    font-size: 11px;
    color: #666;
    line-height: 1.3;
}

.location-address {
    color: #888;
}

.location-phone {
    color: #007bff;
}

.location-hours {
    color: #28a745;
}

.location-type {
    background: #f8f9fa;
    color: #495057;
    padding: 1px 4px;
    border-radius: 2px;
    font-size: 10px;
    display: inline-block;
    margin-top: 1px;
}

/* Element Plus 下拉框选项样式覆盖 */
:deep(.el-select-dropdown__item) {
    height: auto !important;
    min-height: 40px !important;
    padding: 8px 12px !important;
    line-height: 1.4 !important;
    display: flex !important;
    align-items: center !important;
}

:deep(.el-select-dropdown__item.hover) {
    background-color: #f5f7fa !important;
}

:deep(.el-select-dropdown__item.selected) {
    background-color: #e6f7ff !important;
    color: #1890ff !important;
}

/* 下拉框输入框样式 */
:deep(.el-select .el-input__inner) {
    height: 40px !important;
    line-height: 40px !important;
    padding: 0 12px !important;
}

/* 下拉框选中后的显示样式 */
:deep(.el-select .el-input__suffix) {
    display: flex !important;
    align-items: center !important;
}
</style>
